<template>
  <el-dialog
    title="密码修改"
    :visible.sync="open"
    custom-class="dialog"
    @close="dialogClose"
  >
    <div
      class="body"
      v-loading="sendLoading"
      :element-loading-text="loadText"
      element-loading-spinner="el-icon-loading"
    >
      <!-- 1.选择验证方式 -->
      <div class="group" v-if="step == 1">
        <div class="item" @click="chooseType('email')">
          <i class="el-icon-message purple-icon"></i>
          <div class="middle">
            <span class="title">邮箱验证</span>
            <span class="value">{{ user.userEmail || "未填写邮箱" }}</span>
          </div>
          <i class="el-icon-arrow-right"></i>
        </div>
        <el-divider></el-divider>
        <div class="item" @click="chooseType('phone')">
          <i class="el-icon-phone-outline green-icon"></i>
          <div class="middle">
            <span class="title">手机验证</span>
            <span class="value">{{ user.userPhone || "未填写手机号" }}</span>
          </div>
          <i class="el-icon-arrow-right"></i>
        </div>
        <el-divider></el-divider>
        <div class="item" @click="chooseType('password')">
          <i class="el-icon-lock red-icon"></i>
          <div class="middle">
            <span class="title">密码验证</span>
            <span class="value">使用旧密码验证后修改密码</span>
          </div>
          <i class="el-icon-arrow-right"></i>
        </div>
        <el-divider></el-divider>
      </div>
      <!-- 2.1输入验证码 -->
      <div class="step2" v-if="step == 2 && type != 'password'">
        <span class="back el-icon-arrow-left" @click="goBack">返回</span>
        <span class="tip">{{ tipText }}</span>
        <codeInput :emailCode="handleEmailCode" />
        <el-button
          type="primary"
          :disabled="btnText != '重新发送'"
          class="step2btn"
          :loading="codeLoading"
          >{{ btnText }}</el-button
        >
      </div>
      <!-- 2.2输入密码 -->
      <div class="step2" v-if="step == 2 && type == 'password'">
        <span class="back el-icon-arrow-left" @click="goBack">返回</span>
        <span class="tip">{{ tipText }}</span>
        <el-input
          placeholder="请输入密码"
          v-model="password"
          show-password
          class="input"
        ></el-input>
        <!-- <input type="password" placeholder="请输入密码"> -->
        <el-button
          type="primary"
          class="step2btn"
          @click="loginToUpdatePwd"
          :disabled="!password"
          :loading="pwdSending"
          >提交</el-button
        >
      </div>

      <!-- 3.输入新密码并确认 -->
      <div class="step2" v-if="step == 3">
        <div class="temp">
          <span class="step3Span1">新密码</span>
          <el-tooltip
            content="密码是由数字、大写字母、小写字母、特殊符号组成的8-20位字符串"
            placement="bottom-start"
            effect="light"
            v-model="pwdTip"
            manual
          >
            <el-input v-model="newPwd1" show-password class="input"></el-input>
          </el-tooltip>
        </div>
        <div class="temp">
          <span class="step3Span2">确认密码</span>
          <el-tooltip
            content="两次输入密码不一致！"
            placement="bottom-start"
            effect="light"
            v-model="pwdAgainTip"
            manual
          >
            <el-input v-model="newPwd2" show-password class="input"></el-input>
          </el-tooltip>
        </div>
        <!-- <input type="password" placeholder="请输入密码"> -->
        <el-button
          type="primary"
          class="step2btn"
          @click="updatePassword"
          :loading="pwdSending"
          :disabled="!updateEable"
          >修改密码</el-button
        >
      </div>
    </div>
  </el-dialog>
</template>

<script>
const isPwdOk = /^(?=.*[a-zA-Z])(?=.*\d)[a-zA-Z\d\S]{6,20}$/;
import codeInput from "@/components/dialog/codeInput.vue";
import service from "@/utils/request";
export default {
  name: "passwordDialog",
  components: {
    codeInput,
  },
  data() {
    return {
      open: false,
      btnText: "重新发送",
      password: "",
      step: 1,
      type: "",
      sendLoading: false,
      pwdSending: false,
      codeLoading: false,
      phoneOrEmail: "",
      code: "",
      status: "邮箱验证",
      user: "",
      loadText: "验证码发送中...",
      tipText: "请输入旧密码以验证您的身份",
      timer: "",
      newPwd1: "",
      newPwd2: "",
      pwdTip: false,
      pwdAgainTip: false,
    };
  },
  watch: {
    newPwd1(newVal) {
      this.pwdTip = !isPwdOk.test(this.newPwd1) && this.newPwd1 != "";
    },
    newPwd2(newVal) {
      this.pwdAgainTip = this.newPwd1 != this.newPwd2 && this.newPwd2 != "";
    },
  },
  computed: {
    //是否可以注册
    updateEable() {
      return isPwdOk.test(this.newPwd1) && this.newPwd1 == this.newPwd2;
    },
  },
  //监听打开dialog的事件
  created() {
    this.$bus.$on("openDialog", this.openDialog);
  },
  beforeDestroy() {
    this.$bus.$off("openDialog", this.openDialog);
  },
  methods: {
    /**
     * 没有用户信息时请求获取
     */
    // getUserInfo() {
    //   this.loadText = '获取用户信息...'
    //   this.sendLoading = true
    //   service.get('/login/withoutPassword')
    //     .then(res => {
    //       console.log("修改密码--通过免密登录获取用户信息");
    //       //console.log(res);
    //       if (res.code == 200) {
    //         this.loadText = '正在发送验证码...'
    //         this.sendLoading = false
    //         this.user = res.data
    //         localStorage.setItem('user', JSON.stringify(res.data))
    //       }
    //       else {
    //         this.sendLoading = false
    //         this.$router.replace({ path: '/home' });
    //       }
    //     })
    //     .catch(error => {
    //       this.sendLoading = false
    //       this.$message.error("获取用户信息，系统错误！");
    //       console.error('请求出错:', error)
    //       this.$router.replace({ path: '/home' });
    //     })
    // },
    /**
     * 更新密码请求
     */
    updatePassword() {
      const data = {
        userId: this.user.userId,
        userPassword: this.newPwd1,
      };
      service
        .post("user/editPassword", data)
        .then((res) => {
          console.log("修改密码--修改请求响应");
          //console.log(res);
          if (res.code == 200) {
            this.$message.success("修改密码成功，请重新登录！");
            localStorage.removeItem("user");
            localStorage.removeItem("token");
            this.$bus.$emit("updateUserInfo", {});
            this.open = false;
            this.$router.replace({ path: "/home" });
          } else {
            this.$message.warning(`修改密码失败!${res.code}:${res.message}`);
          }
        })
        .catch((error) => {
          this.$message.error("系统错误，验证码发送失败！请稍后重试");
          console.error("系统错误:", error);
        });
    },

    /**
     * 返回选择验证类型
     */
    goBack() {
      this.step = 1;
    },

    /**
     * 验证码完整后的回调函数
     * @param code 输入完成的验证码
     */
    handleEmailCode(code) {
      console.log("验证码已输入:", code);
      this.code = code;
      this.loginByCode();
    },
    /**
     * 通过登录接口验证密码是否正确
     */
    loginToUpdatePwd() {
      this.pwdSending = true;
      const data = {
        userPhone: this.user.userPhone,
        userEmail: this.user.userEmail,
        userPassword: this.password,
      };
      service
        .post("/user/login", data)
        .then((res) => {
          this.pwdSending = false;
          console.log("通过旧密码修改密码响应");
          //console.log(res);
          if (res.code == 200) {
            this.step = 3;
            this.$message.success("验证成功！请修改密码");
          } else {
            this.step = 2;
            this.$message.warning(`验证失败！${res.message}`);
          }
        })
        .catch((error) => {
          this.pwdSending = false;
          this.step = 2;
          this.$message.error(`系统错误！`);
          console.error("请求出错:", error);
        });
    },

    /**
     * 发送验证码
     */
    sendCode() {
      this.sendLoading = true;
      const data = {
        userPhone: "",
        userEmail: "",
      };
      if (this.type == "email") {
        data.userEmail = this.user.userEmail;
        data.userPhone = "";
      } else if (this.type == "phone") {
        data.userPhone = this.user.userPhone;
        data.userEmail = "";
      } else {
        this.$message.error("验证方式异常！");
        return;
      }
      service
        .post("/login/sendCode", data, { timeout: 60000 })
        .then((res) => {
          console.log("验证码修改密码--获取验证码");
          //console.log(res);
          if (res.code == 200) {
            this.$message.success("验证码发送成功！");
            this.user.userId = res.data;
            this.sendLoading = false;
            this.step = 2;
            let minutes = 60;
            this.btnText = `重新发送(${minutes})`;
            this.timer = setInterval(() => {
              minutes--;
              this.btnText = `重新发送(${minutes})`;
              if (minutes <= 0) {
                this.btnText = `重新发送`;
                clearInterval(this.timer);
              }
            }, 1000);
          } else {
            this.sendLoading = false;
            this.step = 1;
            this.$message.warning(`验证码发送失败！${res.message}`);
          }
        })
        .catch((error) => {
          this.sendLoading = false;
          this.step = 1;
          this.codeText = "重新发送";
          if (minutes > 0) {
            clearInterval(this.timer);
          }
          this.$message.error("系统错误，验证码发送失败！请稍后重试");
          console.error("系统错误:", error);
        });
    },
    /**
     * 通过验证码登陆的方式验证
     */
    loginByCode() {
      this.codeLoading = true;
      const data = {
        userId: this.user.userId,
        code: parseInt(this.code),
      };
      service
        .post("/login/byCode", data)
        .then((res) => {
          console.log("验证码修改密码--验证验证码响应");
          //console.log(res);
          if (res.code == 200) {
            this.step = 3;
            this.codeLoading = false;
            this.$message.success("验证成功！请修改密码");
          } else {
            this.codeLoading = false;
            this.step = 2;
            this.$message.warning(`验证失败！${res.message}`);
          }
        })
        .catch((error) => {
          this.codeLoading = false;
          this.step = 2;
          this.$message.error(`系统错误！`);
          console.error("系统错误:", error);
        });
    },

    /**
     * 根据不同选择类型，执行对应操作
     * @param type 选择的验证类型 email phone password
     */
    chooseType(type) {
      if (type == "email") {
        this.$message.warning("暂不支持！");
        // if (!this.user.userEmail) {
        //   this.$message.warning("还未绑定邮箱，无法通过邮箱验证身份！");
        //   return;
        // }
        // this.type = "email";
        // this.tipText = `已经向邮箱【${this.user.userEmail}】发送了验证码, 请注意查收`;
        // this.sendCode();
      } else if (type == "phone") {
        this.$message.warning("暂不支持！");
        // if (!this.user.userPhone) {
        //   this.$message.warning("还未绑定手机号，无法通过手机号验证身份！");
        //   return;
        // }
        // this.type = "phone";
        // this.tipText = `已经向手机【${this.user.userPhone}】发送了验证码, 请注意查收`;
        // this.sendCode();
      } else {
        this.type = "password";
        // this.tipText = `请输入旧密码以验证您的身份`;
        this.step = 2;
      }
    },

    /**
     * 对话框关闭的回调
     */
    dialogClose() {
      this.step = 1;
      //关闭定时器
      if (this.timer) {
        clearTimeout(this.timer);
      }
    },
    /**
     * 其他界面点击打开dialog时的处理
     * @param e 接收到的序号，序号为9时确认是打开这个dialog
     */
    openDialog(e) {
      this.user = JSON.parse(localStorage.getItem("user"));
      if (e == 9) {
        // this.getUserInfo()
        this.open = true;
      }
    },
  },
};
</script>
<style scoped lang="less">
/deep/.dialog {
  width: 400px;
  height: 350px;
  font-weight: 700;
  padding: 0 20px;
  border-radius: 20px;
  display: flex;
  flex-direction: column;

  .body {
    margin-top: -40px;
    width: 100%;
    height: 260px;

    .group {
      width: 100%;
      height: 100%;
      display: flex;
      flex-direction: column;
      margin-top: 30px;
      font-size: 18px;
      font-weight: 700;

      .el-divider {
        width: 98%;
        margin: 0;
        margin-bottom: 20px;
      }

      .item {
        font-weight: 400;
        color: #666666;
        display: flex;
        align-items: center;
        height: 40px;
        position: relative;
        margin: 15px 0px 5px 0;
        padding: 0 5px;
        cursor: pointer;

        .middle {
          width: 70%;

          .title {
            font-size: 12px;
            display: block;
            margin-bottom: 3px;
          }

          .value {
            font-size: 16px;
            display: block;
            color: #171718;
          }
        }

        i:first-of-type {
          height: 40px;
          width: 40px;
          font-size: 26px;
          margin-right: 20px;
          line-height: 40px;
          text-align: center;
          border-radius: 5px;
          background-color: #eee5e5;
        }

        i:last-of-type {
          position: absolute;
          font-size: 18px;
          margin-right: 0;
          font-weight: 700;
          right: 0;
        }
      }

      .item:hover {
        border-radius: 10px;
        background-color: #f0f3f4;
      }
    }

    .step2 {
      width: 100%;
      height: 280px;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      gap: 20px;
      position: relative;

      .tip {
        font-size: 14px;
        text-align: center;
      }

      .step3Span1 {
        position: absolute;
        top: 0;
        left: 10%;
        border-left: 4px solid #503e9d;
        padding: 0 5px;
      }

      .step3Span2 {
        position: absolute;
        top: 0;
        left: 10%;
        border-left: 4px solid #e15d2d;
        padding: 0 5px;
      }

      .temp {
        display: flex;
        flex-direction: column;
        height: 25%;
        justify-content: center;
        align-items: center;
        width: 100%;
        position: relative;
      }

      .input {
        width: 80%;
        height: 30px;
        display: block;
        padding: 5px 5px;
        font-size: 16px;
        font-weight: 700;

        /* 去除聚焦时的外边框 */
        input {
          border: none;
          text-align: center;
          /* 去除所有边框 */
          border-bottom: 0.125rem solid rgba(0, 0, 0, 0.5);
          /* 只保留下边框 */
          outline: none;
        }
      }

      .step2btn {
        width: 80%;
      }

      .back {
        position: absolute;
        top: 10px;
        left: 0;
        cursor: pointer;
      }

      .back:hover {
        color: #4d2fd3;
      }
    }
  }
}

.purple-icon {
  color: #503e9d;
}

.green-icon {
  color: #7dad53;
}

.red-icon {
  color: #fb7545;
}
</style>
